package com.browsesoft.oa;

import java.util.Hashtable;
import java.util.LinkedList;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.browsesoft.Manager;
import com.browsesoft.PropertiesService;

/**
 * 检验管理器
 */
public class VerifyFactory implements Manager {
	/**
	 * 
	 */
	private static final long serialVersionUID = -1107196065509184779L;

	/**
	 * 工厂本身
	 */
	private static VerifyFactory self = null;

	/**
	 * 所有校验器
	 */
	protected LinkedList verifytools = new LinkedList();

	/**
	 * 构造
	 */
	public VerifyFactory() {
		self = this;
	}

	/**
	 * 得到工厂本身
	 * 
	 * @return 工厂
	 */
	public static VerifyFactory getInstance() {
		return self;
	}

	/**
	 * 根据id号得到对象
	 * 
	 * @param id
	 *            id号
	 * @return 对象
	 */
	public Object getObject(String id) {
		return null;
	}

	/**
	 * 装载所有保存的对象
	 * 
	 * @throws Exception
	 */
	public void load() throws Exception {
		// 取得文档对象
		Document doc = (Document) PropertiesService.getDocument();
		Element manager = (Element) doc.getElementsByTagName("VerifyManager")
				.item(0);
		// 取得对象列表
		NodeList list = manager.getChildNodes();
		// 对于每一个校验器
		for (int i = 0; i < list.getLength(); i++) {
			try {
				Node item = (Node) list.item(i);
				// 如果是元素
				if (item instanceof Element) {
					Element element = (Element) item;
					// 得到类名
					String classname = element.getAttribute("classname");
					// 构造
					VerifyTool verifyTool = null;
					ObjectVerifyTool objVerifyTool = null;
					Object obj = Class.forName(classname).newInstance();
					if (obj instanceof VerifyTool) {
						verifyTool = (VerifyTool) obj;
						// 设置标记名
						verifyTool.setKey(element.getTagName());
						// 设置提示
						setHint(verifyTool, element);
						// 添加到链表中
						this.verifytools.add(verifyTool);
					} else if (obj instanceof ObjectVerifyTool) {
						objVerifyTool = (ObjectVerifyTool) obj;
						// 设置标记名
						objVerifyTool.setKey(element.getTagName());
						// 设置提示
						setHint(objVerifyTool, element);
						// 添加到链表中
						this.verifytools.add(objVerifyTool);
					}
				}
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}
	}

	/**
	 * 设置提示
	 */
	private void setHint(VerifyTool tool, Element elem) {
		String hint = elem.getAttribute("hint");
		if (hint != null && !hint.equals("")) {
			tool.setHint(hint);
		}
	}
	
	/**
	 * 设置提示
	 */
	private void setHint(ObjectVerifyTool tool, Element elem) {
		String hint = elem.getAttribute("hint");
		if (hint != null && !hint.equals("")) {
			tool.setHint(hint);
		}
	}

	/**
	 * 得到所有校验器
	 * 
	 * @return 校验器链表
	 */
	public LinkedList getVerifyTools() {
		return (LinkedList) this.verifytools.clone();
	}

	public void synchronAdd(String className, Hashtable attributes) {
	}

	public void synchronRemove(String id) {
	}

	public void synchronUpdate(String id, Hashtable attributes) {
	}
}